﻿#pragma warning disable CS8632
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Text;

namespace Unity.Logger.Providers
{
    public class ConsoleLoggerProvider : ILoggerProvider
    {
        internal const string DefaultOptionName = "ConsoleLogger.Default";

        AsyncStreamLineMessageWriter streamWriter;

        public ConsoleLoggerProvider(IOptionsMonitor<LogOptions> options)
            : this(true, null, options)
        {
        }

        public ConsoleLoggerProvider(bool consoleOutputEncodingToUtf8, string? optionName, IOptionsMonitor<LogOptions> options)
        {
            if (consoleOutputEncodingToUtf8)
            {
                Console.OutputEncoding = new UTF8Encoding(false);
            }

            var opt = options.Get(optionName ?? DefaultOptionName);
            this.streamWriter = new AsyncStreamLineMessageWriter(Console.OpenStandardOutput(), opt);
        }

        public ILogger CreateLogger(string categoryName)
        {
            return new AsyncProcessLog(categoryName, this.streamWriter);
        }

        public void Dispose()
        {
            this.streamWriter.DisposeAsync().AsTask().Wait();
        }
    }
}
